//
//  XKComposeViewController.swift
//  XKWeibo
//
//  Created by 小k on 15/11/20.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit
import SVProgressHUD
//import SnapKit

class XKComposeViewController: UIViewController {
    
    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView {[weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }
    

    // MARK: - 监听方法
     /// 关闭控制器
    @objc private func close () {

        // 关闭键盘
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }

    /// 发送微博
    @objc private func sendStatus () {
        print("发送微博")
        
        // 1. 获取文本类容
        let text = textView.emoticonText
        
        // 2. 发布微博
        NetworkTools.sharedTools.sendStatus(text) { (result, error) -> () in
            
            // 出错
            if error != nil {
                print("出错了")
                SVProgressHUD.showInfoWithStatus("您的网络有错...")
                return
            }
            
            print(result)
            
            //  成功之后关闭控制器
            self.close()
        }
        
    }
    
    /// 选择表情
    @objc private func selectEmoticon () {
        print("选择表情")
        
        // 1. 关闭键盘
        textView.resignFirstResponder()
        
        // 2. 设置表情视图
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        // 3. 重新设置键盘
        textView.becomeFirstResponder()
    }

    // MARK: - 生命周期函数
    override func loadView() {
        view = UIView()
        
        setupUI()
        
    }
    
    // MARK: - 键盘处理
    
    /// 监听键盘变化
    @objc private func keyboardChanged(n: NSNotification) {
        print(n)
        
        // 1.获取动画时长 类型为NSNumber
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        // 2. 获取 NSRect 偏移位子 为 NSValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offset = -view.bounds.height + rect.origin.y
        
        // 获取动画曲线
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        // 3. 设置约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        // 4. 执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            // 设置动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// 注册键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    /// 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        /// 激活键盘
        textView.becomeFirstResponder()
    }
    
    // MARK: - 懒加载控件
    /// 工具条
    private lazy var toolBar = UIToolbar()
    
    /// 文本视图
    private lazy var textView: UITextView = {
       let tv = UITextView()
        
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        
        // 允许垂直滚动
        tv.alwaysBounceVertical = true
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 设置文本视图的代理
        tv.delegate = self
        
        return tv
    }()
    
    /// 占位标签
    private lazy var placeHolderLabel:UILabel = UILabel(title: "分享那些新鲜事...", titleColor: UIColor.grayColor(), titleFont: 18)
    
}

// MARK: - UITextViewDelegate
extension XKComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}


// MARK: - 设置界面
private extension XKComposeViewController {
    /// 设置界面
    func setupUI () {
        
        view.backgroundColor = UIColor.whiteColor()
        
        // 设置控件
        prepareNavigation()
        prepareToolBar()
        prepareTextView()
    }
    
    /// 准备导航栏
    private func prepareNavigation() {
        
        // 1. 设置左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendStatus")
        
        // 默认发送按钮不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 2. 设置标题视图
        // 1>创建控件
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        let titleLabel = UILabel(title: "发微博", titleColor: UIColor.grayColor(), titleFont: 14)
        let nameLabel = UILabel(title: XKUserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", titleColor: UIColor.blackColor(), titleFont: 15)
        
        // 2>添加到视图
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 3>设置布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
        // 4>设置导航栏标题视图
        navigationItem.titleView = titleView
    }
    
    /// 设置工具栏 toolBar
    private func prepareToolBar () {
        // 1. 添加到控制器的View
        view.addSubview(toolBar)
        // 设置背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 2. 自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 3. 添加按钮到items 上
        // 创建图片字典数组
        let itemSetting = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        // 遍历数组常见按钮
        for dictItem in itemSetting {
            
            items.append(UIBarButtonItem(imageName: dictItem["imageName"]!, target: self, actionName: dictItem["actionName"]))
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
            
        }
        // 移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    /// 设置文本视图
    private func prepareTextView () {
        // 1. 添加视图到view
          view.addSubview(textView)
        
        // 2, 设置布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        // 3. 添加占位标签
        // 添加占位标签
        textView.addSubview(placeHolderLabel)
        
        // 设置布局
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
}
